package com.coolrui.domain.statemachine.handler;

import com.alibaba.cola.statemachine.Action;
import com.alibaba.cola.statemachine.Condition;
import com.alibaba.cola.statemachine.impl.StateMachineException;
import com.coolrui.domain.order.entity.UserOrder;
import com.coolrui.domain.order.service.UserOrderDomainService;
import com.coolrui.domain.statemachine.dto.OrderContext;
import com.coolrui.domain.statemachine.enums.OrderEvent;
import com.coolrui.domain.statemachine.enums.OrderPayState;
import com.coolrui.domain.statemachine.enums.OrderState;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 *  用户取消订单 处理
 */
@Slf4j
@Component
public class OrderCancelHandle {
    @Autowired
    private UserOrderDomainService userOrderDomainService;

    public Condition<OrderContext> checkCondition() {
        return (ctx) -> {
            log.info("订单取消检查，订单号:{}", ctx.getOrderId());
            if (ctx.getOrderId() == null) {
                throw new StateMachineException("订单取消失败,参数错误");
            }
            return true;
        };
    }

    @Transactional(rollbackFor = Exception.class)
    public Action<OrderState, OrderEvent, OrderContext> doAction() {
        return (from, to, event, ctx) -> {
            log.info("订单取消执行处理，订单号:{}", ctx.getOrderId());
            // 取消订单更新
            UserOrder userOrder = new UserOrder();
            userOrder.setOrderStatus(OrderState.CANCELED.getCode());
            userOrder.setPayStatus(OrderPayState.REFUND.getCode());
            userOrder.setUpdateTime(new Date());
            int ret = userOrderDomainService.updateOrder(ctx.getOrderId(), userOrder);
            if (ret <= 0) {
                throw new StateMachineException("订单取消失败,更新失败");
            }
        };
    }
}
